package com.vikutorika.service;

import cn.hutool.crypto.digest.BCrypt;
import com.mysql.cj.util.StringUtils;
import com.vikutorika.dao.ManagerAccountInfoDAO;
import com.vikutorika.dao.imp.ManagerAccountInfoDAOImp;
import com.vikutorika.entity.ManagerAccountInfo;
import com.vikutorika.util.CookieUtil;
import com.vikutorika.util.V_DBUtils;
import com.vikutorika.vo.AdminVo;
import com.vikutorika.vo.ResultVo;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.log4j.Log4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;

@Logger
public class AdminService {

	public ResultVo login(AdminVo adminVo, HttpServletRequest req, HttpServletResponse resp) {
		try {
			String username = adminVo.getName();
			String password = adminVo.getPassword();
			ManagerAccountInfoDAO maiDao = new ManagerAccountInfoDAOImp();
			if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)) {
				return ResultVo.error("账号或密码为空");
			} else {
				ManagerAccountInfo manager = maiDao.query(username);
				if (manager != null && BCrypt.checkpw(password, manager.getM_password_hash())) {   // 密码正确
					if (adminVo.getKeepPassword()) {
						CookieUtil.sendCookie(resp, req.getContextPath(), "name", username);
						CookieUtil.sendCookie(resp, req.getContextPath(), "password", username);
					} else {
						CookieUtil.removeCookie(resp, req.getContextPath(), "name");
						CookieUtil.removeCookie(resp, req.getContextPath(), "password");
					}
					if (adminVo.getAutoLogin()) {
						CookieUtil.sendCookie(resp, req.getContextPath(), "autoLogin", "true");
					} else {
						CookieUtil.removeCookie(resp, req.getContextPath(), "autoLogin");
					}
					req.getSession().setAttribute("name", username);
					return ResultVo.success("登录成功");
				} else {    // 密码错误
					return ResultVo.error("账号或密码错误");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultVo.error("服务器发生错误");
		}
	}
}
